package com.travelsky.flash.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.travelsky.flash.api.IProcessWar;
import com.travelsky.flash.constant.ServiceDeployConfigConstant;
import com.travelsky.flash.util.BaseUtil;
import com.travelsky.flash.util.ObjectFileUtil;
import com.travelsky.flash.util.ServerPath;
import com.travelsky.flash.util.log.FlashLogger;
import com.travelsky.flash.util.msg.SendMsgUtil;
import com.travelsky.flash.util.xml.XMLObjUtil;
import com.travelsky.flash.vo.CfgFileVO;
import com.travelsky.flash.vo.DestinationHostVO;
import com.travelsky.flash.vo.SourceHostVO;
import com.travelsky.flash.vo.UserVO;

@Controller  
@RequestMapping("/")  
public class IndexController {
	
	private static FlashLogger logger = new FlashLogger(IndexController.class);
	
	@Resource
	private IProcessWar processWar;
	
	@InitBinder("hostVO")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("hostVO."); 
	}

    /**
     * @Description 首页
     * @return
     * @author syuan
     * @date 2015年5月28日  下午1:36:40
     */
    @RequestMapping("/index")  
    public String toIndex(){
    	return "index";  
    }
    
    @RequestMapping("/toSend") 
    public String toPageSendMsg() {
    	return "demo/demo";
    }
    @RequestMapping("/sendMsg") 
    public String sendMsg(@RequestParam String msg) {
    	SendMsgUtil.sendMsg(msg);
    	return "common/success";
    }
    @RequestMapping("/success") 
    public String success() {
    	return "common/success";
    }
    @RequestMapping("/error") 
    public String error() {
    	return "common/error";
    }
    
    /**
     * @Description 第一步
     * @param hostVO
     * @author syuan
     * @date 2015年5月28日  下午1:36:52
     */
    @RequestMapping("deploy")
    public String deploy(@ModelAttribute("hostVO") SourceHostVO hostVO, HttpSession session) {
    	UserVO user = (UserVO)session.getAttribute(ServiceDeployConfigConstant.USER_SESSION);
    	// 上传配置文件处理
    	manageCfgFiles(hostVO);
    	// 对象写入文件
    	XMLObjUtil.objToXmlFile(ServerPath.getPath(ServerPath.SERVER_UPLOAD_PATH)+"obj-"+ user.getName() +".xml", hostVO);
    	// 部署流程-异步
		processWar.warBuildAndDistribute(hostVO);
		return "show-res";

    }
    @RequestMapping("deployWithFile")
    public String deploy2(HttpSession session) {
    	UserVO user = (UserVO)session.getAttribute(ServiceDeployConfigConstant.USER_SESSION);
    	
    	SourceHostVO hostVO = XMLObjUtil.xmlToObj(ServerPath.getPath(ServerPath.SERVER_UPLOAD_PATH)+"obj-"+user.getName()+".xml");
    	// 部署流程-异步
    	processWar.warBuildAndDistribute(hostVO);
    	
    	return "show-res";
    }
    /**
     * @Description 配置文件处理
     * @param hostVO
     * @author syuan
     * @date 2015年5月29日  上午10:55:47
     */
    private void manageCfgFiles(SourceHostVO hostVO) {
    	FileOutputStream fos = null;
    	File file = null;
    	if(null != hostVO && BaseUtil.listNotNull(hostVO.getDests())) {
    		for(DestinationHostVO dest : hostVO.getDests()) {
    			if(null != dest && BaseUtil.listNotNull(dest.getCfgs())) {
    				for(CfgFileVO cfg : dest.getCfgs()) {
    					if(BaseUtil.stringNotNull(cfg.getWarDir())) {
	    					StringBuffer path = new StringBuffer();
	    					path.append(ServerPath.getPath(ServerPath.SERVER_UPLOAD_PATH))
	    						.append(dest.getHostIp()).append("-").append(dest.getPort());
	    					file = new File(path.toString());
	    					if(!file.exists()) {
	    						file.mkdirs();
	    					}
	    					path.append("/").append(cfg.getFile().getOriginalFilename());
	    					// 写到服务器
	    					try {
	    						file = new File(path.toString());
	    						fos = new FileOutputStream(file);
	    						fos.write(cfg.getFile().getBytes());
	    					} catch (IOException e) {
	    						logger.error("", e);
	    					} finally {
	    						try {
	    							if(null != fos)
	    								fos.close();
	    						} catch (IOException e) {
	    							logger.error("", e);
	    						}
	    					}
	    					
	    					// 设置路径属性
	    					cfg.setServerDir(path.toString());
	    					path.setLength(0);
	    					path.append(ServiceDeployConfigConstant.WORKDIR)
	    						.append(hostVO.getWarName()).append("/")
	    						.append(cfg.getWarDir())
	    						.append("/").append(cfg.getFile().getOriginalFilename());
	    					cfg.setWarDir(path.toString());
	    					cfg.setFile(null);
    					}
    				}
    			}
    		}
    	
    	} 	
    }
}


